<template>
    <div class="bg-white p-4 rounded-lg shadow">
        <!-- 搜索区域 -->
        <div class="mb-4 flex items-center space-x-4">
            <el-input v-model="searchParams.keyword" placeholder="请输入用户名/邮箱" class="!w-60" clearable />
            <el-select v-model="searchParams.status" placeholder="状态" clearable class="!w-32">
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
            </el-select>
            <el-button type="primary" @click="handleSearch">
                <el-icon>
                    <Search />
                </el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
                <el-icon>
                    <Refresh />
                </el-icon>重置
            </el-button>
        </div>

        <!-- 操作按钮区域 -->
        <div class="mb-4">
            <el-button type="primary" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>新增用户
            </el-button>
        </div>

        <!-- 表格区域 -->
        <el-table :data="tableData" border stripe v-loading="loading">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="userName" label="用户名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="role" label="角色" />
            <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                    <el-tag :type="row.status === '1' ? 'success' : 'danger'">
                        {{ row.status === '1' ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
                    <el-button link type="primary" @click="handleReset(row)">重置密码</el-button>
                    <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="mt-4 flex justify-end">
            <el-pagination v-model:current-page="page.current" v-model:page-size="page.size" :total="page.total"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 用户表单对话框 -->
        <el-dialog v-model="dialogVisible" :title="formType === 'add' ? '新增用户' : '编辑用户'" width="500px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="form.userName" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="角色" prop="roleIds">
                    <el-select v-model="form.roleIds" multiple placeholder="请选择角色" class="w-full">
                        <el-option v-for="item in roleOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch v-model="form.status" :active-value="'1'" :inactive-value="'0'" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'

// 搜索参数
const searchParams = reactive({
    keyword: '',
    status: ''
})

// 分页参数
const page = reactive({
    current: 1,
    size: 10,
    total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 表单相关
const dialogVisible = ref(false)
const formType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const form = reactive({
    id: '',
    userName: '',
    email: '',
    roleIds: [],
    status: '1'
})

// 角色选项
const roleOptions = ref([
    { label: '管理员', value: '1' },
    { label: '普通用户', value: '2' }
])

// 表单校验规则
const rules = reactive<FormRules>({
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    roleIds: [
        { required: true, message: '请选择角色', trigger: 'change' }
    ]
})

// 获取表格数据
const getTableData = async () => {
    loading.value = true
    try {
        // TODO: 调用API获取数据
        // const res = await getUserList({ ...searchParams, ...page })
        // tableData.value = res.data.list
        // page.total = res.data.total
    } catch (error) {
        console.error(error)
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    page.current = 1
    getTableData()
}

// 重置搜索
const resetSearch = () => {
    searchParams.keyword = ''
    searchParams.status = ''
    handleSearch()
}

// 新增
const handleAdd = () => {
    formType.value = 'add'
    form.id = ''
    form.userName = ''
    form.email = ''
    form.roleIds = []
    form.status = '1'
    dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
    formType.value = 'edit'
    Object.assign(form, row)
    dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
    ElMessageBox.confirm('确认删除该用户吗？', '提示', {
        type: 'warning'
    }).then(async () => {
        try {
            // TODO: 调用删除API
            // await deleteUser(row.id)
            ElMessage.success('删除成功')
            getTableData()
        } catch (error) {
            console.error(error)
        }
    })
}

// 重置密码
const handleReset = (row: any) => {
    ElMessageBox.confirm('确认重置该用户的密码吗？', '提示', {
        type: 'warning'
    }).then(async () => {
        try {
            // TODO: 调用重置密码API
            // await resetPassword(row.id)
            ElMessage.success('重置密码成功')
        } catch (error) {
            console.error(error)
        }
    })
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // TODO: 调用保存API
                // if (formType.value === 'add') {
                //     await addUser(form)
                // } else {
                //     await updateUser(form)
                // }
                ElMessage.success(formType.value === 'add' ? '新增成功' : '更新成功')
                dialogVisible.value = false
                getTableData()
            } catch (error) {
                console.error(error)
            }
        }
    })
}

// 分页相关
const handleSizeChange = (val: number) => {
    page.size = val
    getTableData()
}

const handleCurrentChange = (val: number) => {
    page.current = val
    getTableData()
}

// 初始化
getTableData()
</script>
